<template>
  <div class="AI" ref="AI">
    <div class="ai-header">
      <div class="sub-title">
        <img src="@/assets/aiIcon.gif" @click="onMax" alt="" />
        <!-- <span> 智能小蓝 </span> -->
      </div>
    </div>
    <div class="ai-content">
      <!-- 消息 -->
      <div class="record resizable-box" :class="{ maximized: isMaximized }">
        <span v-if="flag" style="background:rgba(223, 210, 209)">我：{{message}}</span>
        <span  v-if="flag">AI：{{gptmessage}}</span>
      </div>
      <div class="ribbon">
        <el-scrollbar class="horizontal-scroll">
          <div class="menu">
            <div
              v-for="(item, index) in btnList"
              :key="item"
              @click="clickRoute(item)"
            >
              <div class="delimite" v-if="index === delimiterIndex"></div>
              <span>{{ item?.title }}</span>
            </div>
          </div>
        </el-scrollbar>
        <div class="input">
          <svg-icon name="edit" style="width: 16px; height: 16px" />
          <input
            type="text"
            v-model="message"
            @keydown.enter="send"
            placeholder="你可以向我提问"
            style="
              background: linear-gradient(
                319.35deg,
                rgba(38, 36, 36, 0.4) 15.44%,
                rgba(0, 0, 0, 0.172) 84.72%
              );
              color: #fff;
              font-size: 14px;
            "
          />
          <div @click="send">
            <svg-icon name="send" style="width: 16px; height: 16px" />
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="chat-container" v-if="gptflag">
    <el-button @click="onguanbi">关闭</el-button>
    <div class="messages" ref="messagesRef">
      <div v-for="(msg, index) in messages" :key="index" 
           :class="['message', msg.role]">
        <div class="bubble">
          <span v-if="msg.role === 'ai'">🤖</span>
          <pre v-if="msg.isCode">{{ msg.content }}</pre>
          <span v-else>{{ msg.content }}</span>
          <div v-if="msg.loading" class="loading-dots">
            <span>.</span><span>.</span><span>.</span>
          </div>
        </div>
        <span class="time">{{ msg.time }}</span>
      </div>
    </div>

    <div class="input-area">
      <textarea
        v-model="inputText"
        @keydown.enter.prevent="sendMessage"
        placeholder="输入消息..."
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputText.trim()">
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>

</template>
<script setup>
import { defineProps, reactive } from "vue";

const props = defineProps({
  yjfzSlotHeight: {
    type: String,
    default: "0px",
  },
});

// 对话功能
const isMaximized = ref(false)
const toggleMaximize = () => {
  isMaximized.value = !isMaximized.value
}
const gptflag = ref(false)
const onMax = ()=>{
gptflag.value = true
}
const onguanbi = ()=>{
gptflag.value = false

}


import { useRoute, useRouter } from "vue-router";
import ChatText from "@/components/AI/ChatText.vue";
// import { chatgpt } from "../../api/index.js";
const route = useRoute();
const router = useRouter();
const btnList = [
  {
    title: "患者床头卡",
    name: "PatientCard",
  },
  {
    title: "详情",
    name: "InspectionTesting",
  },
  {
    title: "文件管理",
    name: "FileManagement",
  },
  {
    title: "受邀列表",
    name: "InvitedConsultation",
  },
  {
    title: "申请列表",
    name: "RequestConsultation",
  },
  {
    title: "专家列表",
    name: "Expert",
  },
];
const delimiterIndex = btnList.value?.findIndex((i) => i.type !== 1);
const clickRoute = (route) => {
  console.log("route: ", route);
  router.push({ name: route.name });
};
const chatRecord = ref([]);
const apiUrl = ref("https://api.sizhi.com/chat");
// 聊天功能
const eventSource = ref();
const isClosed = ref(false);
const createEventSource = (message) => {
 
};

// 输入问题
const message = ref("");
// 回复问题

const flag = ref(false)
const gptmessage = ref("")
const send = async () => {
  
  const params = {
    appid: "08ed4648ac5a4b44bff20659112ef07f", // 机器人 ID
    userid: "67890", // 你的用户 ID
    spoken: message.value, // 用户输入的问题
    stream: false, // 是否使用流式传输（布尔值）
    memory: true, // 是否启用对话记忆（布尔值）
  };
  axios
    .get(apiUrl.value, {
      params: params, // 将参数附加到 URL 的查询字符串中
    })
    .then((response) => {
      console.log("机器人回复:", response.data.data.info.text);
      gptmessage.value = response.data.data.info.text;
      flag.value = true
      message.value=""
    })
    .catch((error) => {
      console.error("请求失败:", error);
    });
};
const aiStatus = ref(false);
const AI = ref(null);
const aiHeight = ref(null);
const mapStyle = new Map();
const changeStyle = () => {
  return;
  if (!aiStatus.value) {
    //获取AIref父元素
    let parent = AI.value.parentElement;
    console.log("parent: ", parent);
    //将parent的同级元素全部隐藏
    parent.parentElement.childNodes.forEach((node) => {
      mapStyle.set(node, node.style?.display);
      if (node !== parent) {
        node.style.display = "none";
      } else {
        node.style.display = "block";
      }
    });
    // 将parent元素的高度改为100%
    parent.style.height = "100%";
    aiStatus.value = true;
  } else {
    //获取AIref父元素
    let parent = AI.value.parentElement;
    //将parent的同级元素全部隐藏
    parent.parentElement.childNodes.forEach((node) => {
      node.style.display = mapStyle.get(node);
    });
    // 将parent元素的高度改为100%
    parent.style.height = aiHeight.value + "px";
    console.log(parent.style.height, aiHeight.value);
    aiStatus.value = false;
  }
};
onMounted(() => {
  aiHeight.value = AI.value.parentElement.getBoundingClientRect().height;
});

import axios from 'axios';

// 思知API配置
const API_URL = 'https://api.sizhi.com/chat';
const API_KEY = '08ed4648ac5a4b44bff20659112ef07f';

// 响应式数据
const messages = ref(JSON.parse(localStorage.getItem('chat_history')) || []);
const inputText = ref('');
const isLoading = ref(false);
const messagesRef = ref(null);

// 自动滚动优化（修复点1）
const scrollToBottom = async () => {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight + 100;
  }
};

// 消息发送逻辑重构（修复点2）
const sendMessage = async () => {
  if (!inputText.value.trim() || isLoading.value) return;
  
  try {
    isLoading.value = true;
    
    // 添加用户消息
    const userMsg = {
      role: 'user',
      content: inputText.value,
      time: new Date().toLocaleTimeString(),
      loading: false
    };
    messages.value.push(userMsg);
    
    // 添加AI加载状态
    const aiMsg = { 
      role: 'ai', 
      content: '', 
      time: '', 
      loading: true,
      isCode: false
    };
    messages.value.push(aiMsg);
    
    const userMessage = inputText.value;
    inputText.value = '';
    
    await scrollToBottom(); // 确保DOM更新

    // API请求优化（修复点3）
    const response = await axios.get(API_URL, {
      params: {
        appid: API_KEY,
        userid: 'vue3_chat_user',
        spoken: userMessage
      },
      timeout: 10000 // 添加超时处理
    });

    // 更新AI消息
    const rawContent = response.data.data.info.text;
    const lastAiMsg = messages.value[messages.value.length - 1];
    lastAiMsg.content = rawContent.replace(/```/g, '');
    lastAiMsg.time = new Date().toLocaleTimeString();
    lastAiMsg.isCode = rawContent.includes('```');
    
  } catch (error) {
    console.error('API请求失败:', error);
    messages.value.push({
      role: 'system',
      content: error.response?.data?.message || '服务暂时不可用，请稍后重试',
      time: new Date().toLocaleTimeString()
    });
  } finally {
    isLoading.value = false;
    const lastAiMsg = messages.value[messages.value.length - 1];
    if (lastAiMsg) lastAiMsg.loading = false;
    localStorage.setItem('chat_history', JSON.stringify(messages.value));
    await scrollToBottom();
  }
};

// 初始化滚动
onMounted(() => {
  scrollToBottom();
  // 监听消息变化自动滚动（新增修复点4）
  watch(() => messages.value, scrollToBottom, { deep: true });
});



</script>



<style scoped lang="scss">
.AI {
  width: 100%;
  height: 100%;
  padding-top: 4px;
  position: relative;
  .ai-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 16px;
    svg {
      cursor: pointer;
    }
  }
  .sub-title {
    position: relative;
    display: flex;
    align-items: center;
    ::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 1px; /* 根据需要调整渐变条的高度 */
      background: linear-gradient(
        to right,
        rgba(7, 157, 121, 0.5) 0%,
        rgba(143, 255, 228, 0.5) 30%,
        rgba(7, 157, 121, 0.5) 80%,

        rgba(33, 33, 33, 0.41) 100%
      );
    }
    img {
      width: 45px;
      height: 45px;
      margin-right: 6px;
      height: 100%;
    }
    span {
      color: #fff;
      text-align: center;
      font-family: "Microsoft YaHei", serif;
      font-size: 18px;
      font-style: normal;
      font-weight: 700;
    }
  }
  .ai-content {
    width: 100%;
    height: calc(100% - 32px);
    .record {
      width: 100%;
      height: calc(100% - 96px);
  position: relative;
  border: 2px solid #409eff;
  border-radius: 8px;
  transition: all 0.3s ease;
  overflow: hidden;
      // height: 100%;
      padding: 0 17px 10px;
      //background-color: #fff;
      display: flex;
      flex-direction: column-reverse;
      .self {
        width: fit-content;
        border-radius: 9px 0 9px 9px;
        padding: 5px 10px 5px 5px;
        background: #5e5e5e;
        text-align: right;
        color: #fff;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        margin-left: auto;
      }
    }
.maximized {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toggle-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 6px 12px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  z-index: 10000;
}

.toggle-btn:hover {
  background: #66b1ff;
}
    .ribbon {
      width: 100%;
      height: 96px;
      border-radius: 9px;
      padding: 10px 17px 17px;
      .horizontal-scroll {
        height: 32px;
        overflow-x: auto; /* 只允许横向滚动 */
        overflow-y: hidden; /* 禁止纵向滚动 */
        white-space: nowrap; /* 防止换行，确保子元素在一行显示 */
      }
      .menu {
        width: 100%;
        display: flex;
        // align-items: center;
        margin-bottom: 10px;
        height: 20px;
        div {
          width: auto;
          margin-right: 10px;
          cursor: pointer;
          display: flex;
          align-items: center;
        }
        span {
          color: #fff;
          font-family: "Microsoft YaHei", serif;
          font-size: 12px;
          font-style: normal;
          font-weight: 700;
          border-bottom: 1px solid #17c1c1;
        }
        .delimite {
          display: inline-block;
          width: 1px;
          height: 12px;
          background-color: #000;
          margin-right: 10px;
        }
      }

      .input {
        display: flex;
        width: 100%;
        height: 40px;
        gap: 8px;
        align-items: center;
        // border-radius: 9px;
        border: 2px solid rgba(71, 69, 69, 0.24);
        // border-image-source: linear-gradient(
        //   91.28deg,
        //   rgba(71, 69, 69, 0.24) 1.61%,
        //   rgba(0, 0, 0, 0.4) 98.1%
        // );

        background: linear-gradient(
          319.35deg,
          rgba(38, 36, 36, 0.4) 15.44%,
          rgba(0, 0, 0, 0.172) 84.72%
        );

        padding: 0 8px;
        input {
          width: calc(100% - 16px - 16px - 18px);
          height: 24px;
          border: none;
          outline: none;
        }
        div {
          display: flex;
          align-items: center;
          margin-left: auto;
          cursor: pointer;
        }
        // div {
        //   display: flex;
        //   align-items: center;
        //   justify-content: center;
        //   width: 49px;
        //   height: 27px;
        //   margin-left: auto;
        //   border-radius: 6px;
        //   border: 1px solid #a6a6a6;
        //   background: #dcdcdc;
        //   cursor: pointer;
        // }
      }
    }
  }

  
}
ul,
ol {
  list-style: initial;
}
b,
strong {
  font-weight: initial;
}

.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 12px;
  height: 80vh;
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 70px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
}

.message {
  margin: 10px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.bubble {
  max-width: 70%;
  padding: 12px 18px;
  border-radius: 15px;
  background: #343d44;
  position: relative;
  white-space: pre-wrap;
}

.message.user .bubble {
  background: #2196f3;
  color: white;
}

.loading-dots span {
  opacity: 0;
  animation: dot 1.5s infinite;
}

@keyframes dot {
  0%, 40%, 100% { opacity: 0; }
  20% { opacity: 1; }
}

.input-area {
  display: flex;
  gap: 10px;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  height: 80px;
}

button {
  padding: 12px 24px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  align-self: flex-end;
}

button:disabled {
  background: #90caf9;
  cursor: not-allowed;
}

.time {
  font-size: 12px;
  color: #666;
  align-self: flex-end;
  margin: 0 8px;
}

pre {
  background: #282c34;
  color: #abb2bf;
  padding: 10px;
  border-radius: 6px;
  overflow-x: auto;
}


</style>
